<?php

namespace app\common\model;

use app\common\exception\BusinessException;
use think\db\exception\DbException;
use think\facade\Db;
use think\Model;

class AgentRelation extends Base
{
    /**
     * 开启自动时间戳
     * @var bool
     */
    protected $autoWriteTimestamp = false;

    /**
     * 创建时间戳
     * @var string
     */
    protected $createTime = 'create_time';

    /**
     * 更新时间戳
     * @var string
     */
    protected $updateTime = 'update_time';

    public $relation_level_map = [
        '1' => '一级',
        '2' => '二级',
    ];

    /**
     * add
     * @param $child_uid
     * @param $parent_id
     * @return void
     * @throws BusinessException
     */
    public function add($child_uid, $parent_id)
    {
        // 开启事务
        $this->startTrans();

        // 保存一级关系
        $this->checkAndAdd($parent_id, $child_uid, 1);

        // 保存二级关系
        $parent_parent_id = $this->getParentUid($parent_id, 1);
        if ($parent_parent_id) {
            $this->checkAndAdd($parent_parent_id, $child_uid, 2);
        }

        // 提交事务
        $this->commit();
    }

    /**
     * getParentUid
     * @param $child_uid
     * @param $relation_level
     * @return mixed
     */
    public function getParentUid($child_uid, $relation_level)
    {
        $where = [
            ['child_uid', '=', $child_uid],
            ['relation_level', '=', $relation_level]
        ];
        return $this->field('parent_uid')->where($where)->value('parent_uid', 0);
    }

    /**
     * hasParent
     * @param $uid
     * @return boolean
     * @throws DbException
     */
    public function hasParent($uid): bool
    {
        $where = [
            ['child_uid', '=', $uid],
        ];
        return (bool)$this->where($where)->count();
    }

    /**
     * checkAndAdd
     * @param $parent_id
     * @param $child_uid
     * @param $relation_level
     * @throws
     */
    private function checkAndAdd($parent_id, $child_uid, $relation_level)
    {
        // 查询是否存在关系
        $where = [
            ['child_uid', '=', $child_uid],
            ['relation_level', '=', $relation_level]
        ];
        $count = $this->where($where)->count();

        // 保存关系
        if (!$count) {
            $time = time();
            $saveData = [
                'parent_uid' => $parent_id,
                'child_uid' => $child_uid,
                'relation_level' => $relation_level,
                'create_time' => $time,
                'update_time' => $time,
            ];
            if (!$this->add_data($saveData)) {
                throw new BusinessException('保存分销关系失败');
            }
        }
    }

    /**
     * getAllParentIdByChildUid
     * @param $child_uid
     * @return array
     */
    public function getAllParentByChildUid($child_uid): array
    {
        // 查询条件
        $where = [
            ['child_uid', '=', $child_uid],
        ];

        // 返回
        return $this->where($where)->select()->toArray();
    }
}